﻿using NLog;
using System;
using System.Threading;
using HslCommunication.Profinet.Melsec;
using HslCommunication;
using IOA.MES.Client.Common;
using HslCommunication.Profinet.Siemens;
using System.Threading.Tasks;

namespace IOA.MES.Client.Framing.PLCUtils
{

    public delegate void OnTcpStatusChange(bool connected);
    public class McNetClient
    {
        public MelsecMcNet mcNet;
        private FramingIndex index;
        private bool isHeartBeating = false;
        private OnTcpStatusChange onStatusChange;
        private int heartBeatData;
        private int headBeatMilSecs;
        public OperateResult connect;
        private static string ReadPLC = "D400";
        private static string WritePLC = "D402";
        public McNetClient(FramingIndex index, string ipAddress, int port,
            //OnTcpStatusChange onStatusChange, OnDataReceived onDataReceived,
            OnTcpStatusChange onStatusChange,
            int heartBeatData, int headBeatMilSecs)
        {
            this.index = index;
            this.onStatusChange = onStatusChange;
            //this.onDataReceived = onDataReceived;
            //this.OnChangePhoto = OnChangePhoto;
            this.heartBeatData = heartBeatData;
            this.headBeatMilSecs = headBeatMilSecs;
            mcNet = new MelsecMcNet(ipAddress, port);
            //西门子
            //SiemensS7Net siemensS7Net = new SiemensS7Net(SiemensPLCS.S1500,ipAddress);
            //siemensS7Net.Port = port;
            //siemensS7Net.Rack = 0;//机架号
            //siemensS7Net.Slot = 1;//PLC槽号
        }

        /// <summary>
        /// 连接到服务端
        /// </summary>
        public async void Connect()
        {
            CommonMessage.Log(LogLevel.Debug, $"准备连接PLC：{mcNet.IpAddress}:{mcNet.Port}");
            mcNet.ConnectTimeOut = 2000; // 网络连接的超时时间
            mcNet.NetworkNumber = 0x00;  // 网络号
            mcNet.NetworkStationNumber = 0x00; // 网络站号
            connect = mcNet.ConnectServer();
            if (connect.IsSuccess)
            {
                CommonMessage.Log(LogLevel.Debug, $"连接PLC成功：{mcNet.IpAddress}:{mcNet.Port}");
                if (onStatusChange != null)
                {
                    onStatusChange(true);
                }
                if (!isHeartBeating)
                {
                    //isHeartBeating = true;
                    //Thread thread = new Thread(heartBeat);
                    //thread.IsBackground = true;
                    //thread.Start();
                    //异步运行heartBeat方法
                    //await Task.Run(heartBeat);
                }
            }
            else
            {
                CommonMessage.Log(LogLevel.Fatal, "Connect Error");
                await index.Dispatcher.BeginInvoke(new Action(() =>
                {
                    CommonMessage.Alert(index, $"无法连接PLC:{mcNet.IpAddress}:{mcNet.Port}");
                }));
            }
        }

        /// <summary>
        /// 采用线程间隔一秒发送数据，防止界面卡死
        /// </summary>
        private void heartBeat()
        {
            while (isHeartBeating)
            {
                //给1秒钟的时间修改数据
                Thread.Sleep(2000);
                heartBeatData = mcNet.ReadInt16(ReadPLC).Content;
                CommonMessage.Log(LogLevel.Info, $"PLC寄存器{ReadPLC}接到的数据：{heartBeatData}");
                if (heartBeatData == 1)//执行拍照程序
                {
                    CommonMessage.Log(LogLevel.Info, $"执行拍照函数");
                    //异步执行拍照函数
                    //AsyncToDo();
                    index.TodoAutoPhoto();
                    CommonMessage.Log(LogLevel.Info, $"自动扫码拍照完成");
                    Thread.Sleep(headBeatMilSecs + 3000);
                }
                else
                {
                    Thread.Sleep(headBeatMilSecs - 2000);
                }
            }
        }
        public async void AsyncToDo()
        {
            await Task.Run(() =>
            {
                index.TodoAutoPhoto();
            });
        }
        /// <summary>
        /// 向PLC发送数据
        /// </summary>
        public void Send(int heartBeatData)
        {
            if (connect.IsSuccess)
            {
                mcNet.Write(ReadPLC, -1);
                CommonMessage.Log(LogLevel.Debug, $"写入成功，往PLC寄存器{ReadPLC}写入的数据是：-1");
                //if (heartBeatData != -1)
                //{
                //    mcNet.Write(WritePLC, heartBeatData);
                //    CommonMessage.Log(LogLevel.Info, $"往{WritePLC}中写入数据发成功：{heartBeatData}");
                //}
                //Thread.Sleep(500);
                mcNet.Write(WritePLC, heartBeatData);
                CommonMessage.Log(LogLevel.Debug, $"往{WritePLC}中写入数据成功：{heartBeatData}");
            }
            else
            {
                CommonMessage.Alert(index, $"与流水线的PLC连接断开，取消发送数据，请检查网络：");
                CommonMessage.Log(LogLevel.Debug, $"PLC不可用，取消发送数据：{heartBeatData}");
            }
        }
        /// <summary>
        /// 向PLC发送数据
        /// </summary>
        public int Read()
        {
            int ret = -1;
            if (connect.IsSuccess)
            {
                ret = mcNet.ReadInt16(ReadPLC).Content;
                CommonMessage.Log(LogLevel.Debug, $"PLC寄存器{ReadPLC}读到的数据：{ret}");
            }
            else
            {
                CommonMessage.Alert(index, $"与流水线的PLC连接断开，接受不到数据，请检查网络：");
                CommonMessage.Log(LogLevel.Debug, $"PLC寄存器{ReadPLC}不可用，读到：{ret}");
            }
            return ret;
        }
    }
        
}
